<template>
  <el-dialog :title="title" :visible.sync="visible" width="500px" :before-close="handleClose">
    <el-form :rules="rules" ref="formData" :model="formData" label-width="100px" label-position="right"
             style="width: 400px" status-icon
    >
      <el-form-item label="用户名：" prop="username">
        <el-input v-model="formData.username" maxlength="30"></el-input>
      </el-form-item>
      <el-form-item label="昵称：" prop="nickName">
        <el-input v-model="formData.nickName" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label="手机号：" prop="mobile">
        <el-input v-model="formData.mobile" maxlength="11"></el-input>
      </el-form-item>
      <el-form-item label="头像：" prop="imageUrl">
        <img :src="formData.imageUrl" title="点击上传头像" class="avatar" @click="toggleShow">
        <my-upload
          @crop-success="cropSuccess"
          @crop-upload-success="cropUploadSuccess"
          @crop-upload-fail="cropUploadFail"
          field="file"
          v-model="show"
          :headers="{'satoken': this.$store.getters.token}"
          :url="url"
          method="post"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('formData')" size="mini">确定</el-button>
        <el-button size="mini" @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import 'babel-polyfill'; // es6 shim
import myUpload from 'vue-image-crop-upload/upload-2.vue';
import * as api from '@/api/user'
import { mapGetters } from 'vuex'


export default {
  components: {
    'my-upload': myUpload
  },
  computed: {
    ...mapGetters(['token'])
  },
  props: {
    title: { // 弹窗的标题
      type: String,
      default: ''
    },
    visible: { // 弹出窗口，true弹出
      type: Boolean,
      default: false
    },
    formData: { // 提交表单数据
      type: Object,
      default: {
      }
    },
    remoteClose: Function // 用于关闭窗口
  },

  data() {
    return {
      url: 'http://localhost:8082/pri/file/upload/user',
      headers: {'satoken': this.token},
      // 校验表单
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
        ],

        nickName: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],

        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],

        isAccountNonExpired: [
          { required: true, message: '请选择', trigger: 'change' }
        ],

        isCredentialsNonExpired: [
          { required: true, message: '请选择', trigger: 'change' }
        ],

        isAccountNonLocked: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      show: false
    }
  },

  methods: {
    cropSuccess(imgDataUrl, field){
      this.formData.imageUrl = imgDataUrl;
    },
    cropUploadSuccess(jsonData, field){
      console.log(jsonData);
      this.formData.imageUrl = jsonData.data
    },
    cropUploadFail(status, field){
      this.$message.error("图像上传失败")
    },
    uploadMainImg(file) {
      // 封装表单对象
      const data = new FormData()
      data.append('file', file.file)
      // 发送请求上传
      this.uploadImg(data).then(response => {
        this.$message.success('上传成功')
        this.formData.imageUrl = response.data
      }).catch(() => {
        this.$message.error('上传失败')
      })
    },
    toggleShow() {
      this.show = !this.show
    },
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 校验通过，提交表单数据
          this.submitData()
        } else {
          // console.log('error submit!!');
          return false
        }
      })
    },

    async submitData() {
      let response = null
      if (this.formData.id) {
        // 编辑
        response = await api.update(this.formData)
      } else {
        // 新增
        // 初始密码与用户名一致
        this.formData.password = this.formData.username
        response = await api.add(this.formData)
      }

      if (response.code = 20000) {
        this.$message({ message: '保存成功', type: 'success' })
        this.handleClose()
      } else {
        this.$message({ message: '保存失败', type: 'error' })
      }
    },

    // 关闭窗口
    handleClose() {
      this.show = false
      this.$refs['formData'].resetFields()
      this.remoteClose()
    }

  }
}
</script>
<style scoped rel="stylesheet/scss" lang="scss">
.avatar {
  width: 160px;
  height: 160px;
}
</style>
